<template>
  <main class="main">
    <el-alert
      style="position: fixed; top: 0; z-index: 3"
      :title="`答题即将在 ${END_ANSWER_TIME} 结束`"
      type="success"
      :closable="false"
    >
    </el-alert>
    <header class="header"><div>上海宋庆龄故居 · FDU20CS2</div></header>
    <transition name="slide">
      <div class="action-bar" v-if="show">
        <el-button
          class="submit-button"
          @click="
            submitAnswer(
              question.type === 0
                ? currentRadioAnswer
                : question.type === 1
                ? currentCheckboxAnswer.join(',')
                : currentTextAnswer
            )
          "
          >{{
            this.currentQuestion === this.questionCount
              ? "提交并结束答题"
              : "提交"
          }}</el-button
        >
      </div>
    </transition>
    <!-- 题目 -->
    <transition name="slide">
      <div v-if="show" :style="question.type === 2 ? 'min-width: 60%' : ''">
        <div class="question">{{ question.title }}</div>

        <!-- 加入图片 -->
        <div class="demo-image">
          <el-image
            style="width: 400px; height: 500px"
            :src="question.examImage"
            :fit="fit"
          >
          </el-image>
        </div>

        <!-- 单选 -->
        <div v-if="question.type === 0" style="text-align: center">
          <el-radio-group
            style="display: block; width: fit-content; margin: 0 auto"
            v-model="currentRadioAnswer"
            size="small"
          >
            <transition
              v-for="(item, index) in question.options"
              :key="question.id + index"
              appear
              name="slide"
            >
              <el-radio
                style="display: flex; margin: 20px 0; text-align: left"
                :label="LABELLIST[index]"
                border
                >{{ item }}</el-radio
              >
            </transition>
          </el-radio-group>
        </div>
        <!-- 多选 -->
        <div v-if="question.type === 1" style="text-align: center">
          <el-checkbox-group v-model="currentCheckboxAnswer" size="small">
            <transition
              v-for="(item, index) in question.options"
              :key="question.id + index"
              appear
              name="slide"
            >
              <el-checkbox
                style="display: flex; margin: 20px 0; text-align: left"
                :label="LABELLIST[index]"
                border
              >
                {{ item }}
              </el-checkbox>
            </transition>
          </el-checkbox-group>
        </div>
        <!-- 填空 -->
        <div v-if="question.type === 2" style="text-align: center">
          <transition appear name="slide">
            <el-input
              style="text-align: left"
              type="textarea"
              :rows="5"
              placeholder="请输入内容"
              v-model="currentTextAnswer"
            >
            </el-input>
          </transition>
        </div>
      </div>
    </transition>
    <StatusBar
      class="bottom-bar"
      :count="questionCount"
      :current="currentQuestion"
      :setQuestion="moveQuestion.bind(this)"
    />
    <ResultPage v-if="isEnd" :result="true" :score="totalScore" />
  </main>
</template>

<script>
import { mapState, mapMutations } from "vuex";
// import Option from "@/components/Option";
import ResultPage from "@/components/ResultPage";
import { GET_USER_INFO } from "@/store/mutation-types";
import StatusBar from "@/components/StatusBar";
import { getQuestion, personalRank, saveAnswer } from "@/api";

export default {
  name: "QuizView",
  data() {
    return {
      input: "",
      show: false,
      question: {
        type: 0,
        title: "测试问题",
        options: ["好的", "不好的"],
        id: "",
        examImage: "",
      },
      currentRadioAnswer: undefined,
      currentCheckboxAnswer: [],
      currentTextAnswer: undefined,
      questionList: {},
      questionCount: 0, // 总题数
      currentQuestion: 1, // 当前第几题
      isEnd: false, // 是否结束（全部答对或答错一题）
      totalScore: 0, // 总分
      LABELLIST: [
        "A",
        "B",
        "C",
        "D",
        "E",
        "F",
        "G",
        "H",
        "I",
        "J",
        "K",
        "L",
        "M",
        "N",
      ],
    };
  },
  methods: {
    resetData() {
      this.show = false;
      this.isRight = false;
      this.restTime = 10;
      this.input = "";
    },
    showQuestion() {
      // 获取题目
      getQuestion(this.token).then((response) => {
        if (response.data.code === 500) {
          this.$message({ type: "error", message: "无权限访问" });
        } else {
          this.questionCount = response.data.page.totalCount;
          this.questionList = response.data.page.list;
          this.setQuestion(0);
        }
      });
    },
    submitAnswer(answer) {
      if (answer === undefined || answer.length === 0) {
        this.$message({ type: "warning", message: "回答为空" });
        return;
      }
      saveAnswer(
        {
          userId: this.userId,
          examAnswer: answer,
          examId: this.question.id,
        },
        this.token
      ).then((res) => {
        if (res.data.code === 0) {
          this.currentRadioAnswer = undefined;
          this.currentCheckboxAnswer = [];
          this.currentTextAnswer = undefined;
          if (this.currentQuestion === this.questionCount) {
            setTimeout(() => {
              this.showResult();
            }, 200);
          } else {
            this.moveQuestion(this.currentQuestion);
          }
        } else {
          this.$message({ type: "error", message: res.data.msg });
        }
      });
    },
    moveQuestion(questionIdx) {
      // 播放动画后继续下一题
      this.resetData();
      setTimeout(() => {
        this.setQuestion(questionIdx);
        this.currentQuestion = questionIdx + 1;
      }, 500);
    },
    setQuestion(questionIdx) {
      this.show = true;
      const current = this.questionList[questionIdx];
      if (typeof current.examOptions === "string") {
        current.examOptions = current.examOptions.split("\n");
      }
      this.question.id = current.examId;
      this.question.type = current.examType;
      this.question.title = current.examTitle;

      // added
      this.question.examImage = current.examImage;

      if (current.examOptions != null && current.examOptions.length > 0) {
        this.question.options = current.examOptions;
      }
    },
    showResult() {
      // 展示答题完成结果
      personalRank().then((res) => {
        const rankList = res.data.rank;
        this.totalScore = rankList.find(
          ({ userId }) => userId === this.userId
        ).score;
        this.isEnd = true;
      });
    },
    ...mapMutations({
      getUserInfo: GET_USER_INFO,
    }),
  },
  created() {
    this.resetData();
  },
  mounted() {
    this.getUserInfo();
    this.$nextTick(() => {
      this.showQuestion();
    });
  },
  beforeUnmount() {
    clearInterval(this.countdownInterval);
  },
  watch: {},
  computed: {
    ...mapState(["userId", "token", "userId", "END_ANSWER_TIME"]),
  },
  components: {
    // Option,
    ResultPage,
    StatusBar,
  },
};
</script>

<style lang="scss" scoped>
.main {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  overflow: hidden;
  .header {
    width: 100%;
    height: 36vh;
    position: relative;
    background-color: #d32f2f;
    // background: url("~@/assets/quiz-background.png") no-repeat center center;
    // background-size: 100% 100%;
    div {
      position: absolute;
      bottom: 4px;
      right: 10px;
      color: #fbc051;
      font-style: italic;
      font-family: cursive;
      font-weight: bold;
    }
  }
  .background {
    margin-top: -68px;
    width: 0;
    height: 0;
    border-left: 44px solid transparent;
    border-right: 44px solid transparent;
    border-bottom: 40px solid #fff;
  }
  .clock {
    margin-top: -38px;
    width: 68px;
    height: 68px;
    box-sizing: border-box;
    border: 6px solid #fff;
  }
  .animation {
    display: block;
    border-radius: 50%;
    background-color: #fff;
    z-index: 1;
  }
  .path {
    stroke-dasharray: 1000;
    stroke-dashoffset: 0;
  }
  .circle {
    animation: dash 0.9s ease-in-out;
  }
  .line {
    stroke-dashoffset: 1000;
    animation: dash 0.9s 0.35s ease-in-out forwards;
  }
  .check {
    stroke-dashoffset: -100;
    animation: dash-check 0.9s 0.35s ease-in-out forwards;
  }
  .action-bar {
    width: 100%;
    padding-top: 17px;
    margin-right: 30px;
    text-align: right;
    .submit-button {
      padding: 8px 10px 7px 10px;
      background-color: #ffe195;
      border-color: #c49000;
      color: #a57a04;
    }
  }
  @keyframes dash {
    0% {
      stroke-dashoffset: 1000;
    }
    100% {
      stroke-dashoffset: 0;
    }
  }
  @keyframes dash-check {
    0% {
      stroke-dashoffset: -100;
    }
    100% {
      stroke-dashoffset: 900;
    }
  }
  // 题目
  .question {
    margin: 30px 15px 10px;
    text-align: center;
    color: #444;
    font-size: 19px;
    line-height: 24px;
    font-weight: 600;
  }
  // 选项
  .options {
    width: 60%;
    margin: 0 auto;
    padding: 0;
    list-style: none;
    // 选项进入效果
    .slide-enter-active {
      &:nth-child(2) {
        transition-delay: 0.1s;
      }
      &:nth-child(3) {
        transition-delay: 0.2s;
      }
      &:nth-child(4) {
        transition-delay: 0.3s;
      }
      &:nth-child(5) {
        transition-delay: 0.4s;
      }
    }
    .slide-leave-active {
      &:nth-child(2) {
        transition-delay: 0.1s;
      }
      &:nth-child(3) {
        transition-delay: 0.2s;
      }
      &:nth-child(4) {
        transition-delay: 0.3s;
      }
      &:nth-child(5) {
        transition-delay: 0.4s;
      }
    }
  }
  // 题目进入动画
  .slide-enter-active {
    transition: all 0.8s;
  }
  .slide-leave-active {
    transition: all 0.6s;
  }
  .slide-enter {
    transform: translateX(100vw);
  }
  .slide-leave-to {
    transform: translateX(-100vw);
  }
  .bottom-bar {
    position: absolute;
    bottom: 24px;
  }
}
</style>
